//
//  Created by DevilsEyes on 2016/2/13.
//  ================================
//              抓取算法
//  ================================
'use strict';

var $doc = require('../../model/doc.js');
var $stats = require('../../model/stats.js');
var config = require('../../unit/config.js');
var request = require('request');
var option = require('../../unit/req_options.js');

var formatLink = require('./formatLink.js');
var analysis = require('./analysis.js');

class Captor {
    constructor(doc) {
        let noop = ()=> {
        };

        let request_callback = noop,
            update_callback = noop,
            interrupt_callback = noop;

        this.doc = doc;

        this.request_done = (cb)=> {
            request_callback = cb;
            return this;
        };
        this.update_done = (cb)=> {
            update_callback = cb;
            return this;
        };
        this.interrupt = (cb)=> {
            interrupt_callback = cb;
            return this;
        };

        this.start = ()=> {

            var doc = this.doc;

            request(option.set(doc.link),
                (err, res, html) => {
                    request_callback();
                    if (html == null || doc.status == -1) {

                        console.log('弃用:' + doc.link);

                        $doc.update(doc.id, {status: -1})
                            .then(() => {
                                interrupt_callback('链接已弃用');
                                //todo 这里, 到底该放个字符串? 还是该放个错误?
                            });
                        return;
                    }
                    switch (doc.deep) {
                        case 0:
                        {
                            //抓取根节点的链接
                            if (doc.root.match('B')) {
                                extract.baidu(doc, html);
                            } else if (doc.root.match('G')) {
                                extract.google(doc, html);
                            } else {
                                //noop
                            }
                            doc.status = 1;
                            break;
                        }
                        case config.deepMax:
                        {
                            //仅计算末端节点的匹配度
                            doc = analysis(doc, html);
                            break;
                        }
                        default :
                        {
                            //标准状态,计算匹配度->抓取链接
                            doc = analysis(doc, html);

                            if (doc.status > 1) {
                                extract.normal(doc, html);
                            } else {
                                //noop
                                //无关页面不再采集链接
                            }
                            break;
                        }
                    }
                    $doc.update(doc.id, doc)
                        .exec((err, doc)=> {
                            if (err) {
                                interrupt_callback(err);
                            } else {
                                update_callback(doc);
                            }
                        });
                });

            return this;
        }
    }
}

var extract = {
    baidu: (doc, html) => {
        var Reg = /<h3 class="t"><a[\s\S]+?<\/h3>/g;
        html.replace(Reg, (str) => {
            var link = str.match(/href[\s]*=[\s]*["']([^\s"'#]+)/)[1];
            var title = str.match(/<a[\s\S]+?>([\s\S]+?)<\/a>/)[1];

            link = formatLink(link, doc);
            if (link === false)return str;

            $doc.isRepeated(link)
                .then(() => {
                    $doc.save({
                        link: link,
                        title: title,
                        status: 0,
                        deep: 1,
                        root: doc.root,
                        path: doc.path + '>' + link
                    }).then(()=> {
                        //noop
                    });
                })
                .catch((err)=> {
                    //noop
                });

            return str;
        })
    },
    google: (doc, html) => {

        //link = formatLink(link, doc);
        //if (link === false)return str;
        //
        //$doc.getByLink(link, (check) => {
        //    if (!check) {
        //        $doc.save({
        //            link: link,
        //            title: title,
        //            status: 0,
        //            deep: 1,
        //            root: doc.root,
        //path:doc.path + '>' + link
        //        });
        //    } else {
        //        //noop
        //    }
        //});
        //
        //return str;

    },
    normal: (doc, html) => {
        var Reg = /href[\s]*=[\s]*["']([^\s"'#]+)/g;
        html.replace(Reg, (str) => {
            var link, title;
            try {
                link = str.match(/href[\s]*=[\s]*["']([^\s"'#]+)/)[1];
            } catch (e) {
                return str;
            }

            link = formatLink(link, doc);
            if (link === false)return str;

            try {
                title = str.match(/<a[\s\S]+?>([\s\S]+?)<\/a>/)[1];
            } catch (e) {
                title = '';
            }

            $doc.isRepeated(link)
                .then(() => {
                    $doc.save({
                        link: link,
                        title: title,
                        status: 0,
                        deep: doc.deep + 1,
                        root: doc.root,
                        path: doc.path + '>' + link
                    }).then(()=> {
                        //noop
                    });
                })
                .catch((err)=> {
                    //noop
                });

            return str;
        })
    }
};

module.exports = Captor;